package Core;

import java.util.Vector;

public class ContextMenu extends Form
{
	private Point mountPoint = new Point();
	private Vector actions = new Vector();
	private Form owner;
	private int align;

	public ContextMenu(Form owner)
	{
		super(Form.NO_FS | Form.NO_CENTRALISE | Form.NO_BG, owner.getW()/3*2, 0);
		body.spacing = -1;

		body.allowToEnlarge = true;
		form.allowToEnlarge = true;
		
		GUICanvas.manager.closeUpperForm();

		this.owner = owner;
	}

	public void show(Point mount, int align)
	{
		this.align = align;
		mountPoint.x = mount.x;
		mountPoint.y = mount.y;

		if((align & ALIGN.BOTTOM) == ALIGN.BOTTOM) mount.y -= getH();
		if((align & ALIGN.RIGHT)  == ALIGN.RIGHT)  mount.x -= getW();
		if((align & ALIGN.CENTER) == ALIGN.CENTER)
		{
			mount.x -= getW()/2;
			mount.y -= getH()/2;
		}

		coord.x = Math.max(mount.x, 0);
		coord.y = Math.max(mount.y, 0);

		if(coord.y + getH() > GUICanvas.manager.getH())
			coord.y = GUICanvas.manager.getH() - getH();

		if(coord.x + getW() > GUICanvas.manager.getW())
			coord.x = GUICanvas.manager.getW() - getW();

		GUICanvas.manager.addForm(this);

		if(!actions.isEmpty()) body.switchSelectTo(body.getControl(0));
	}
	
	public void addAction(ContextAction a)
	{
		body.addControl(a.button);
		actions.addElement(a);
	}

	public void onEvent(int event, Object param)
	{
		super.onEvent(event, param);
		
		ContextAction a;

		if(event == GM.CONTROL_RELEASED)
		{
			for(int i=0; i<actions.size(); i++)
			{
				a = (ContextAction) actions.elementAt(i);
				
				if(param == a.button)
				{
					GUICanvas.manager.closeUpperForm();
					
					if(a.menu == null) owner.onEvent(GM.CONTEXT_RELEASED, a);
					else a.menu.show(mountPoint, align);

					return;
				}
			}
		}
	}

}
